/**
 * 
 */
package org.xlab.baseframework.aspect;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.xlab.baseframework.annotation.Security;
import org.xlab.baseframework.common.entity.AbstractSystemBean;
import org.xlab.baseframework.domain.SystemWebServiceSession;
import org.xlab.baseframework.exception.InactiveWebServiceSessionFoundexception;
import org.xlab.baseframework.exception.PermissionDeniedException;
import org.xlab.baseframework.exception.SystemWebServiceSessionNotFoundException;
import org.xlab.baseframework.service.api.ISystemWebServiceSessionService;

/**
 * @author makubex
 * 
 */
@Component
public class SecurityAcpectForWebService extends AbstractSystemBean {

	/**
	 * @serialField
	 */
	private static final long serialVersionUID = 8540466598987783102L;
	private static final Logger log = Logger
			.getLogger(SecurityAcpectForWebService.class);
	@Autowired(required = true)
	@Qualifier("bpf_systemWSSessionService")
	private ISystemWebServiceSessionService systemWebServiceSessionService;

	public void checkSession(Security security, String sessionId,
			String clientId) throws PermissionDeniedException {
		if (security.value()) {
			try {
				log.debug("Checking session[" + sessionId + "]...");
				SystemWebServiceSession session = this.systemWebServiceSessionService
						.findBySessionId(sessionId);
				if (!session.getClientId().equalsIgnoreCase(clientId)
						|| this.systemWebServiceSessionService
								.checkExpired(sessionId)) {
					throw new PermissionDeniedException();
				}
			} catch (SystemWebServiceSessionNotFoundException e) {
				throw new PermissionDeniedException(e);
			} catch (InactiveWebServiceSessionFoundexception e) {
				throw new PermissionDeniedException(e);
			}
		}
	}

	/**
	 * @return the systemWebServiceSessionService
	 */
	public ISystemWebServiceSessionService getSystemWebServiceSessionService() {
		return systemWebServiceSessionService;
	}

	/**
	 * @param systemWebServiceSessionService
	 *            the systemWebServiceSessionService to set
	 */
	public void setSystemWebServiceSessionService(
			ISystemWebServiceSessionService systemWebServiceSessionService) {
		this.systemWebServiceSessionService = systemWebServiceSessionService;
	}
}
